package com.example.productiontestble;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothGatt;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleMtuChangedCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.example.productiontestble.model.DeviceModel;
import com.example.productiontestble.utils.AnimUtils;
import com.example.productiontestble.utils.BluetoothKey;
import com.example.productiontestble.utils.ByteUtils;
import com.example.productiontestble.utils.KLog;
import com.example.productiontestble.utils.ScanRecord;

import java.nio.charset.StandardCharsets;

public class DetailsActivity extends BaseActivity implements View.OnClickListener {

    private BleDevice bleDevice;

    private DeviceModel deviceModel;

    private ImageView mImageBack;

    private Button mDisBtn, mWaringBtn;

    private TextView mNameTv, mTmpTv, mHumTv, mRssiTv;

    private ProgressDialog progressDialog;

    private MaterialDialog dialog;

    private boolean isEmptyData = false;

    private Handler mRssiHandler = new Handler();

    private Runnable mRssiRunnable = new Runnable() {
        @Override
        public void run() {
            if (!isEmptyData) {
                readRssi();
            } else {
                sendBleMsg(0x3d);
            }
            mRssiHandler.postDelayed(mRssiRunnable, 1000);
        }
    };

    @Override
    public int getLayoutId() {
        return R.layout.activity_details;
    }


    @Override
    public void initView() {

        getLastPageData();

        initDialog();

        mImageBack = findViewById(R.id.details_back);
        mDisBtn = findViewById(R.id.layout_back);
        mWaringBtn = findViewById(R.id.layout_waring);

        mImageBack.setOnClickListener(this);
        mDisBtn.setOnClickListener(this);
        mWaringBtn.setOnClickListener(this);

        mNameTv = findViewById(R.id.details_name);
        mTmpTv = findViewById(R.id.details_tmp);
        mHumTv = findViewById(R.id.details_hum);
        mRssiTv = findViewById(R.id.details_rssi);

        if (bleDevice != null) {
            byte[] scanRecord = ScanRecord.parseFromBytes(bleDevice.getScanRecord())
                    .getManufacturerSpecificData(BluetoothKey.FEATURES);
            mNameTv.setText("C-" + new String(scanRecord, 6, 5, StandardCharsets.US_ASCII));
        }

        connectBle(bleDevice);


    }

    /**
     * 初始化dialog
     */
    private void initDialog() {

        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("连接中,请稍后...");
        progressDialog.setCancelable(false);
        progressDialog.show();

        View view;
        view = LayoutInflater.from(this).
                inflate(R.layout.dialog_tip, null, false);

        dialog = new MaterialDialog.Builder(this)
                .backgroundColor(0x00ffffff)
                .customView(view, false)
                .build();
        TextView tCancel = view.findViewById(R.id.tv_cancel);
        tCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dialog.dismiss();
            }
        });
        view = dialog.getCustomView();
        TextView tConfirm = view.findViewById(R.id.tv_confirm);
        tConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                finish();
            }
        });

    }

    /**
     * 刷新UI
     */
    private void refreshUI() {
        if (deviceModel != null) {

            if (deviceModel.isDegree) {
                mTmpTv.setText("温度：" + (deviceModel.tmp) / 100 + "°C");
                mHumTv.setText("湿度：" + (deviceModel.hum) / 100 + "%");
            } else {
                mTmpTv.setText("温度：" + (deviceModel.tmp) / 100 + "℉");
                mHumTv.setText("湿度：" + (deviceModel.hum) / 100 + "%");
            }


        }

    }

    /**
     * 连接蓝牙
     *
     * @param bleDevice
     */
    private void connectBle(BleDevice bleDevice) {

        new Handler(Looper.getMainLooper()).postDelayed(() -> BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                KLog.i("连接状态==》开始连接！");
            }

            @Override
            public void onConnectFail(BleDevice bleDevice1, BleException exception) {
                KLog.i("连接状态==》连接失败！");
                Toast.makeText(DetailsActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                finish();
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice1, BluetoothGatt gatt, int status) {
                KLog.i("连接状态==》连接成功！");

                BleManager.getInstance().setMtu(bleDevice1, BluetoothKey.DEFAULT_MTU, new BleMtuChangedCallback() {
                    @Override
                    public void onSetMTUFailure(BleException exception) {

                    }

                    @Override
                    public void onMtuChanged(int mtu) {

                        KLog.e("设置MTU成功：" + mtu);


                        BleManager.getInstance().notify(bleDevice1, BluetoothKey.UUID_SERVICE, BluetoothKey.UUID_NOTIFY, new BleNotifyCallback() {
                            @Override
                            public void onNotifySuccess() {
                                KLog.e("onNotifySuccess:");
                                progressDialog.dismiss();
                                mRssiHandler.postDelayed(mRssiRunnable, 200);
                            }

                            @Override
                            public void onNotifyFailure(BleException exception) {

                            }

                            @Override
                            public void onCharacteristicChanged(byte[] data) {
                                KLog.e("接收数据===》：" + data[0] + "///" + data[1]
                                        + "///" + ByteUtils.bytes2HexString(data));
                                //30///-1///0x1e,0xff,0x02,0x09,0x4c,0x3b,0x0b,0x38,0xc1,0xa4,0x4e,0x30,0x38,0x34,0x31,0x00,0x04,0x49,0x00,0x01,0x18,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0xff,
                                //-91///16///0xa5,0x10,0x00,0x03,0x00,0x0a,0x50,0x79,0x00,0x01,0x3f,0x01,0x4e,0x14,0x17,
                                if (data[0] == 0x1e && data[1] == (byte) 0xff) {
                                    deviceModel = CResolution.parseInfo(data);
                                    refreshUI();
                                }
                                if (data[0] == -91 && data[1] == 16) {
                                    if (byteToHex(data[10]).equals("3f")) {
                                        KLog.e("接收数据===》1：读取rssi：" + ByteUtils.bytes2HexString(data));
                                        int rssi = byteToHexInt(data[12]) - 110;
                                        mRssiTv.setText("RSSI：" + rssi);
                                    } else if (byteToHex(data[10]).equals("3d")) {//清除数据
                                        //0xa5,0x10,0x00,0x02,0x00,0x0a,0x67,0x49,0x00,0x03,0x3d,0x00,0xae,0x59,
                                        KLog.e("接收数据===》1：清除数据：" + ByteUtils.bytes2HexString(data));
                                        progressDialog.dismiss();
                                        if (byteToHexInt(data[11]) == 0) {
                                            mRssiHandler.removeCallbacks(mRssiRunnable);
                                            Toast.makeText(DetailsActivity.this, "清除成功", Toast.LENGTH_SHORT).show();
                                            BleManager.getInstance().disconnect(bleDevice);
                                            finish();
                                        }

                                    } else if (byteToHex(data[10]).equals("3e")) {//立即报警
                                        //0xa5,0x10,0x00,0x02,0x00,0x0a,0x67,0x49,0x00,0x03,0x3e,0x00,0xfb,0x0a,
                                        KLog.e("接收数据===》1：立即报警：" + ByteUtils.bytes2HexString(data));
                                    }

                                }

                            }
                        });


                    }
                });

            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                KLog.i("断开连接！");
                mRssiHandler.removeCallbacks(mRssiRunnable);
                progressDialog.dismiss();
                finish();
                mRssiHandler.removeCallbacks(mRssiRunnable);
            }
        }), 100);


    }

    //转16进制
    public static String byteToHex(byte b) {
        String hex = Integer.toHexString(b & 0xFF);
        if (hex.length() < 2) {
            hex = "0" + hex;
        }
        return hex;
    }

    //转10进制
    public static int byteToHexInt(byte b) {
        String hex = Integer.toHexString(b & 0xFF);
        if (hex.length() < 2) {
            hex = "0" + hex;
        }
        return Integer.parseInt(hex, 16);
    }

    private void getLastPageData() {
        Intent intent = getIntent();
        if (null != intent) {
            bleDevice = intent.getParcelableExtra(BluetoothKey.BLE_DEVICE);
        }
    }


    /**
     * 读取rssi
     * 0xa5,0x10,0x00,0x03,0x00,0x0a,0x50,0x79,0x00,0x01,0x3f,0x01,0x54,0xa7,0x6c,
     */
    private void readRssi() {
        BleManager.getInstance().write(bleDevice, BluetoothKey.UUID_SERVICE,
                BluetoothKey.UUID_WRITE, CResolution.getRssi(10), false, new BleWriteCallback() {
                    @Override
                    public void onWriteSuccess(int current, int total, byte[] justWrite) {
                        KLog.e("写入成功：" + ByteUtils.bytes2HexString(justWrite));
                    }

                    @Override
                    public void onWriteFailure(BleException exception) {

                    }
                });
    }

    /**
     * 发送警报
     */
    private void sendBleMsg(int dataId) {

        if (dataId == 0x3d) {
            if (!progressDialog.isShowing()) {
                progressDialog.setMessage("清除数据中...");
                progressDialog.show();
            }

        }

        BleManager.getInstance().write(bleDevice, BluetoothKey.UUID_SERVICE,
                BluetoothKey.UUID_WRITE, CResolution.setSettingData(10, dataId), false, new BleWriteCallback() {
                    @Override
                    public void onWriteSuccess(int current, int total, byte[] justWrite) {
                        KLog.e("写入成功：--" + ByteUtils.bytes2HexString(justWrite));
                    }

                    @Override
                    public void onWriteFailure(BleException exception) {

                    }
                });

    }

    public static void startActivity(Activity activity, BleDevice bleDevice) {
        Intent intent = new Intent(activity, DetailsActivity.class);
        intent.putExtra(BluetoothKey.BLE_DEVICE, bleDevice);
        AnimUtils.startActivity(activity, intent, AnimUtils.SLIDE_TO_LEFT);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.details_back:
                dialog.show();
                break;
            case R.id.layout_back:
                isEmptyData = true;
                break;
            case R.id.layout_waring:
                sendBleMsg(0x3e);
                break;
            default:
                break;

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bleDevice != null && BleManager.getInstance().isConnected(bleDevice)) {
            BleManager.getInstance().disconnect(bleDevice);
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            dialog.show();
            return true;

        }
        if (keyCode == KeyEvent.KEYCODE_SEARCH) {
            KLog.d("+++++>2");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}


